package com.xj0927.cloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.TimeUnit;

/**
 * @Author: xj0927
 * @Description:
 * @Date Created in 2020-10-30 9:02
 * @Modified By:
 */
@Service
public class PaymentService {

    public String payment_ok(Integer id){
        return Thread.currentThread().getName() + "payment_ok,id:" + id;
    }

    @HystrixCommand(fallbackMethod = "paymentInfo_TimeOutHandler",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    public String payment_outTime(Integer id){
        int time = 3;
//        int time = 10/0; //模拟异常
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return Thread.currentThread().getName() + "payment_outTime,id:" + id;
    }
    //对应处理措施
    public String paymentInfo_TimeOutHandler(Integer id){
        return Thread.currentThread().getName() + "paymentInfo_TimeOutHandler" + "服务超时或者异常";
    }

    /** 服务熔断 */
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启熔断器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到多少后跳闸
    })
    public String paymentCircuitBreaker(Integer id){
        if(id < 0){
            throw new RuntimeException("id不能为负数****");
        }
        String serialNumber = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "调用成功，流水号" + serialNumber;
    }
    //先进行相应的服务降级的方法
    public String paymentCircuitBreaker_fallback(Integer id){
        return "id 不能为负数,请稍后再试~~ " + id;
    }
}
